<template>
    <div class="my-ads-container">
        <!-- 页面标题 -->
        <div class="page-header">
            <div class="header-left">
                <h1>我的广告</h1>
                <el-tag type="info" class="total-count">共 {{ total }} 条</el-tag>
            </div>
            <el-button type="primary" @click="$router.push('/advertiser/create-ad')">
                <el-icon>
                    <Plus />
                </el-icon>创建广告
            </el-button>
        </div>

        <!-- 搜索区域 -->
        <el-form :model="queryParams" ref="queryForm" :inline="true" class="search-form">
            <el-form-item label="广告标题" prop="title">
                <el-input v-model="queryParams.title" placeholder="请输入广告标题" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="广告类型" prop="type">
                <el-select v-model="queryParams.type" placeholder="请选择类型" clearable style="width: 180px">
                    <el-option v-for="(label, value) in typeOptions" :key="value" :label="label"
                        :value="Number(value)" />
                </el-select>
            </el-form-item>
            <el-form-item label="投放状态" prop="status">
                <el-select v-model="queryParams.status" placeholder="请选择状态" clearable style="width: 180px">
                    <el-option v-for="(label, value) in statusOptions" :key="value" :label="label"
                        :value="Number(value)" />
                </el-select>
            </el-form-item>
            <el-form-item label="投放时间" prop="dateRange">
                <el-date-picker v-model="queryParams.dateRange" type="daterange" range-separator="至"
                    start-placeholder="开始日期" end-placeholder="结束日期" value-format="YYYY-MM-DD" />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="handleQuery">
                    <el-icon>
                        <Search />
                    </el-icon>查询
                </el-button>
                <el-button @click="resetQuery">
                    <el-icon>
                        <Refresh />
                    </el-icon>重置
                </el-button>
            </el-form-item>
        </el-form>

        <!-- 广告列表 -->
        <el-card v-loading="loading">
            <el-table :data="adList" border stripe style="width: 100%">
                <el-table-column prop="id" label="ID" width="80" align="center" />
           <el-table-column label="广告素材" width="120" align="center">
    <template #default="{ row }">
        <!-- 有素材的情况 -->
        <template v-if="row.advertising">
            <!-- 视频广告使用截图 -->
            <el-image 
                v-if="row.type === 3"
                style="width: 80px; height: 50px" 
                :src="`${row.advertising}?x-oss-process=video/snapshot,t_1000,f_jpg,w_200,h_120,m_fast`" 
                fit="cover"
                :preview-src-list="[row.advertising]"
            />
            <!-- 其他类型广告直接显示 -->
            <el-image 
                v-else
                style="width: 80px; height: 50px" 
                :src="row.advertising" 
                fit="cover"
                :preview-src-list="[row.advertising]"
            />
        </template>
        
        <!-- 无素材的情况显示占位内容 -->
        <div v-else class="no-media-placeholder">
            <el-icon><Picture /></el-icon>
            <div class="placeholder-text">
                {{ row.type === 1 ? '文字广告' : 
                   row.type === 2 ? '图片广告' : 
                   row.type === 3 ? '视频广告' : '未设置类型' }}
            </div>
        </div>
    </template>
</el-table-column>
                <el-table-column label="广告标题" prop="title" min-width="180" show-overflow-tooltip>
                    <template #default="{ row }">
                        <el-link type="primary" @click="viewAdDetails(row.id)">{{ row.title }}</el-link>
                    </template>
                </el-table-column>
                <el-table-column label="广告类型" width="120" align="center">
    <template #default="{ row }">
        <el-tag v-if="row.type !== null" :type="getTypeTagType(row.type)">
            {{ typeOptions[row.type] || '--' }}
        </el-tag>
        <el-tag v-else type="info">未设置</el-tag>
    </template>
</el-table-column>
                <el-table-column label="投放时间" align="center" width="300">
                    <template #default="{ row }">
                        <div>{{ formatTime(row.startTime) }}</div>
                        <div>至</div>
                        <div>{{ formatTime(row.endTime) }}</div>
                    </template>
                </el-table-column>
                <el-table-column prop="budget" label="预算" width="120" align="right">
                    <template #default="{ row }">
                        <span>¥{{ Number(row.budget).toFixed(2) }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="状态" width="100" align="center">
                    <template #default="{ row }">
                        <el-tag :type="getStatusType(row.status)">
                            {{ statusOptions[row.status] }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="创建时间" width="180" align="center">
                    <template #default="{ row }">
                        {{ formatTime(row.createdTime) }}
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="180" fixed="right" align="center">
                    <template #default="{ row }">
                        <el-button-group>
                            <el-button link type="primary" @click="viewAdDetails(row.id)">查看</el-button>
                            <el-button link type="primary" :disabled="!canEdit(row.status)" @click="editAd(row.id)">
                                编辑
                            </el-button>
                            <el-button link type="danger" :disabled="!canDelete(row.status)" @click="handleDelete(row)">
                                删除
                            </el-button>
                        </el-button-group>
                    </template>
                </el-table-column>
            </el-table>

            <!-- 分页 -->
            <div class="pagination-container">
                <el-pagination v-model:current-page="queryParams.pageNum" v-model:page-size="queryParams.pageSize"
                    :page-sizes="[10, 20, 50, 100]" :total="total" layout="total, sizes, prev, pager, next, jumper"
                    @size-change="handleSizeChange" @current-change="handleCurrentChange" />
            </div>
        </el-card>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search, Refresh, Picture } from '@element-plus/icons-vue'
import { getMyAdvertisements, deleteAdvertisement } from '@/api/advertisement'


const router = useRouter()
const loading = ref(false)
const adList = ref([])
const total = ref(0)

// 获取类型标签样式
const getTypeTagType = (type) => {
    const typeMap = {
        1: 'info',     // 文字广告
        2: 'success',  // 图片广告
        3: 'warning'   // 视频广告
    }
    return typeMap[type] || 'info'
}
// 获取广告缩略图
// 获取广告缩略图
const getAdThumbnail = (row) => {
    // 使用 OSS 视频截图服务，但只有在确定是视频广告且有链接时才使用
    if (row.type === 3 && row.advertising) {
        try {
            return `${row.advertising}?x-oss-process=video/snapshot,t_1000,f_jpg,w_200,h_120,m_fast`
        } catch (e) {
            console.error("Error generating thumbnail:", e);
            // 如果生成缩略图出错，返回默认占位图
            return '/placeholder.png'
        }
    }
    
    // 如果有广告素材但不是视频，直接返回
    if (row.advertising) {
        return row.advertising
    }
    
    // 没有素材时返回静态占位图（确保这个路径是正确的）
    return '@/assets/11.jpg'
}
// 查询参数
const queryParams = reactive({
    pageNum: 1,
    pageSize: 10,
    title: '',
    status: '',
    type: '',
    dateRange: []
})

// 广告类型选项
const typeOptions = {
  1: '文字广告',
  2: '图片广告',
  3: '视频广告',
}

// 状态选项
const statusOptions = {
    0: '待审核',
    1: '已审核',
    2: '投放中',
    3: '已完成',
    4: '已拒绝'
}

// 获取列表数据
const getList = async () => {
    loading.value = true
    try {
        const params = {
            pageNum: queryParams.pageNum,
            pageSize: queryParams.pageSize,
            title: queryParams.title || undefined,
            status: queryParams.status || undefined,
            type: queryParams.type || undefined,
            startDate: queryParams.dateRange?.[0],
            endDate: queryParams.dateRange?.[1]
        }

        const res = await getMyAdvertisements(params)
        console.log(res)
        if (res.data.code === 200) {
            console.log(res.data.data.records)
            console.log(res.data.data.total)
            adList.value = res.data.data.records || []
            total.value = res.data.data.total || 0
        } else {
            ElMessage.error(res.message || '获取列表失败')
        }
    } catch (error) {
        console.error('获取列表失败:', error)
        ElMessage.error('获取列表失败')
    } finally {
        loading.value = false
    }
}

// 查询
const handleQuery = () => {
    queryParams.pageNum = 1
    getList()
}

// 重置
const resetQuery = () => {
    queryParams.title = ''
    queryParams.status = ''
    queryParams.type = ''
    queryParams.dateRange = []
    handleQuery()
}

// 处理删除
const handleDelete = (row) => {
    ElMessageBox.confirm('确定要删除该广告吗？此操作不可逆', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(async () => {
        try {
            const res = await deleteAdvertisement(row.id)
            console.log(res)
            if (res.data.code === 200) {
                ElMessage.success('删除成功')
                getList()
            } else {
                ElMessage.error(res.message || '删除失败')
            }
        } catch (error) {
            console.error('删除失败:', error)
            ElMessage.error('删除失败')
        }
    })
}

// 查看详情
const viewAdDetails = (id) => {
    router.push(`/advertiser/ad-details/${id}`)
}

// 编辑广告
const editAd = (id) => {
    router.push(`/advertiser/edit-ad/${id}`)
}

// 格式化时间
const formatTime = (time) => {
    if (!time) return '--'
    return new Date(time).toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
    }).replace(/\//g, '-')
}

// 获取状态类型
const getStatusType = (status) => {
    const typeMap = {
        0: 'info',
        1: 'success',
        2: 'primary',
        3: 'success',
        4: 'danger'
    }
    return typeMap[status] || 'info'
}

// 是否可以编辑
const canEdit = (status) => {
    return [0, 4].includes(status)
}

// 是否可以删除
const canDelete = (status) => {
    return [0, 4].includes(status)
}

// 分页大小改变
const handleSizeChange = () => {
    queryParams.pageNum = 1
    getList()
}

// 页码改变
const handleCurrentChange = () => {
    getList()
}

onMounted(() => {
    getList()
})
</script>

<style scoped>
.my-ads-container {
    padding: 20px;
}

.page-header {
    margin-bottom: 20px;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.header-left {
    display: flex;
    align-items: center;
    gap: 12px;
}

.header-left h1 {
    margin: 0;
    font-size: 24px;
    font-weight: 500;
}

.total-count {
    font-size: 14px;
}

.search-form {
    background-color: #fff;
    padding: 18px 20px;
    margin-bottom: 20px;
    border-radius: 4px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: center;
}

.el-button-group {
    display: flex;
    gap: 8px;
}

.el-image {
    border-radius: 4px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}
.no-media-placeholder {
    width: 80px;
    height: 50px;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    background-color: #f5f7fa;
    border-radius: 4px;
    color: #909399;
}

.no-media-placeholder .el-icon {
    font-size: 24px;
    margin-bottom: 4px;
}

.placeholder-text {
    font-size: 12px;
    line-height: 1;
    text-align: center;
}
</style>